import moment from 'moment'
import Cookies from 'js-cookie'
import { ref } from 'vue'

const KEY = 'accessToken'
interface AccessToken {
  token: string
  expires: Date | string
  keepSession: boolean
}

let remove = ref<boolean>(false)
const AccessToken: AccessToken = { token: '', expires: new Date(), keepSession: false }
// 设置token
const initToken = (access_token: any = {}) => {
  const token = access_token?.token ?? ''
  const expires = access_token?.ttl ?? null
  const keepSession = access_token?.keepSession ?? false
  if (token) {
    AccessToken.token = token
    AccessToken.expires = expires
    AccessToken.keepSession = keepSession
    Cookies.set(KEY, JSON.stringify({ token, expires, keepSession }), {
      expires: new Date(expires)
    })
  } else {
    let _token = Cookies.get(KEY)
    try {
      _token = JSON.parse(_token as string)

      if (typeof _token != 'object') {
        _token = ""
      }
    } catch {
      _token = ""
    }

    if (_token) {
      AccessToken.token = _token.token
      AccessToken.expires = _token.expires
      AccessToken.keepSession = _token.keepSession
    }
  }
  remove.value = false
  checkTokenRefresh()
}
let timerId = 0

// import emitter from '@/plugin/eventbus'
// 检测Token刷新
const checkTokenRefresh = () => {
  console.log('过期时间', AccessToken.expires)
  if (AccessToken.keepSession && AccessToken.token) {
    // 过期时间减去3分钟在现在时间之前，说明快要到过期时间了，刷新
    if (moment(AccessToken.expires).subtract(3, 'minute').isBefore(new Date())) {
      console.log('刷新token')
      refreshToken()
    }
  }
  // 1分钟检查一次
  timerId = setTimeout(() => {
    checkTokenRefresh()
  }, 60 * 1000)
  console.log(moment(AccessToken.expires).isBefore(new Date()), !AccessToken.expires)
  // 已过期 或者 AccessToken.expires == ""(刷新token失败时)
  if (moment(AccessToken.expires).isBefore(new Date()) || !AccessToken.expires) {
    removeToken()
    // emitter.emit('showLoginPopup')
    // 移除定时检查setTimeout
    if (timerId) {
      clearTimeout(timerId)
      timerId = 0 // 清除引用
    }
  }
}
// 刷新token
const refreshToken = () => {
  // const dno = loginStore.device_no
  // LoginApi.RefreshToken({
  //   // dno
  // }).then(({ data }: any) => {
  //   const token = data.data.token
  //   const expires = data.data.ttl
  //   const keepSession = data.data.keep_session
  //   AccessToken.token = token
  //   AccessToken.expires = expires
  //   // 重新存储token和过期时间
  //   Cookies.set(KEY, JSON.stringify({ token, expires, keepSession }), {
  //     expires: new Date(expires)
  //   })
  // })
}
// 提供外部获取token
const getToken = () => {
  let _token = Cookies.get(KEY)
  if (!_token) return
  _token = JSON.parse(_token)
  // token到过期时间或主动清除token
  if (moment(_token.expires).isBefore(new Date()) || remove.value) {
    AccessToken.token = ''
    AccessToken.expires = ''
    console.log('token过期')
  }
  return _token.token
}
// 提供外部token过期时间
const getTokenExpires = () => {
  let _token = Cookies.get(KEY)
  if (!_token) return
  return _token.expires
}

// 清楚token
const removeToken = () => {
  Cookies.remove(KEY)
  remove.value = true
}
const Token = {
  initToken,
  getToken,
  removeToken,
  getTokenExpires
}

export default Token
